<template>
  <div class="home" v-loading="loading">
    <div class="layout">
      <el-table
        :data="tableData"
        :span-method="arraySpanMethod"
        >
        <el-table-column label="" v-for="(item,index) in 12" :key="index">
          <template #default="{ row }">
            <el-button class="size1" :class="{'hide': !layoutIndexs.includes(row[index])}">
              <div v-if="isHasSetting(row[index]) != null">
                <img class="cardPic" :src="isHasSetting(row[index]).cardPic" />
              </div>
              <div class="setting" @click.stop="cellClick(row[index])" v-if="isHasSetting(row[index]) == null">配置</div>
              <div class="d-flex" v-else >
                <div class="setting mr-3" @click.stop="cellClick(row[index])">更换</div>
                <div class="setting" @click.stop="setData(row[index])">配置参数</div>
              </div>
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="footer">
      <el-button type="primary" @click="saveCardSetting">保存</el-button>
      <el-button @click="goBack()">返回</el-button>
    </div>

    <!-- 配置卡片弹框 -->
    <yc-dialog ref="cardDialog" :centerTitle="centerTitle" :dialogTitle="dialogTitle">
      <template #content>
        <div class="dialog-content">
          <el-form :inline="true">
            <el-form-item label="组件标题">
              <el-input
                v-model="searchCardName"
                placeholder="请输入组件标题"
              />
            </el-form-item>

          </el-form>
          <div v-for="(cards, index) in cardList" :key="index">
            <div class="cardtitle">{{ cards.name }}</div>
            <div class="cardList" v-if="cards.list">
              <div class="d-flex flex-column align-items-center" v-for="item in cards.list" :key="item.id">
                <img :src="item.cardPic" @click="cardCode = item.cardCode" />
                <el-radio v-model="cardCode" :label="item.cardCode">{{item.cardName}}</el-radio>
              </div>
            </div>
          </div>
        </div>
      </template>
      <template #footer>
        <el-button type="primary" :loading="cardLoading" @click="cardSave">确定</el-button>
        <el-button @click="$refs.cardDialog.dialogVisible = false">取消
        </el-button>
      </template>
    </yc-dialog>

    <!-- 配置参数弹框 -->
    <yc-dialog ref="setDataDialog" :dialogWidth="'70%'" :centerTitle="centerTitle" :dialogTitle="dialogTitle">
      <template #content>
        <div class="dialog-content">
            <div class="d-flex justify-content-between align-items-end">
              <div>已选择参数</div>
              <el-button
                type="primary"
                @click="addParams"
                size="medium"
              >添加参数
              </el-button>
            </div>
            <el-table
              :data="selectList"
              border
              style="width: 100%;"
              class="elTable"
            >
              <el-table-column type="index" label="序号" width="50" align="center"/>
              <el-table-column prop="valueShowData" label="数据值" align="center"/>
              <el-table-column prop="valueName" label="数据名称" align="center"/>
              <el-table-column prop="valueDataType" label="数据值类型" align="center">
                <template #default="{ row }">
                  <span>{{row.valueDataType == 1 ? "布尔类型" : "一般类型"}}</span>
                </template>
              </el-table-column>
              <el-table-column prop="customerCode" label="客户编码" align="center"/>
              <el-table-column prop="customerName" label="客户名称" align="center"/>
              <el-table-column prop="tagName" label="区域标签" align="center"/>
              <el-table-column prop="deviceName" label="设备标签" align="center"/>
              <el-table-column prop="deviceCode" label="设备编码" align="center"/>
              <el-table-column prop="deviceDicName" label="设备类型标签" align="center"/>
              <el-table-column prop="valueCode" label="参数编码" align="center"/>
              <el-table-column prop="aggregationDicName" label="聚合规则名称" show-overflow-tooltip align="center"/>
              <el-table-column label="操作" width="300" align="center">
                <template #default='{ row }'>
                  <span v-if="row.valueDataType == 1">
                    <el-button type="primary" size="mini" @click="settingIcon(row, '0')">{{row.zeroValue}}icon</el-button>
                    <el-button type="primary" size="mini" @click="settingIcon(row, '1')">{{row.oneValue}}icon</el-button>
                    <el-button type="danger" size="mini" @click="removeData(row)">删除</el-button>
                  </span>
                  <span v-else>
                    <el-button type="primary" size="mini" @click="settingIcon(row)">配置icon</el-button>
                    <el-button type="danger" size="mini" @click="removeData(row)">删除</el-button>
                  </span>
                </template>
              </el-table-column>
            </el-table>
        </div>
      </template>
      <template #footer>
        <el-button type="primary" :loading="setDataLoading" @click="setDataSave">确定</el-button>
        <el-button @click="$refs.setDataDialog.dialogVisible = false">取消
        </el-button>
      </template>
    </yc-dialog>

    <!-- 选择照片 -->
    <yc-dialog ref="iconDialog" :centerTitle="centerTitle2" :dialogTitle="dialogTitle2">
      <template #content>
        <div class="dialog-content2">
          <div class="d-flex flex-wrap">
            <div class="d-flex align-items-center flex-column mr-4 mb-4" v-for="(item ,index) in picList" :key="index">
              <div class="picdiv mb-2">
                <img :src="item.picUrl" class="bgcss" @click="iconUrl = item.picUrl" />
              </div>
              <el-radio :label="item.picUrl" v-model="picUrl">{{ item.picName }}</el-radio>
            </div>
          </div>
        </div>
      </template>
      <template #footer>
        <el-button type="primary" @click="iconSave">确定</el-button>
        <el-button @click="$refs.iconDialog.dialogVisible = false">取消
        </el-button>
      </template>
    </yc-dialog>

    <!-- 添加参数弹框 -->
    <yc-dialog ref="addParamsDialog" :dialogWidth="'70%'" :centerTitle="centerTitle2" :dialogTitle="dialogTitle2">
      <template #content>
        <div class="dialog-content">
          <el-form :inline="true" :model="formInline" size="small" class="demo-form-inline">
            <el-form-item label="区域标签">
              <el-cascader
                clearable
                v-model="formInline.tagCode"
                :options="dimensionalityTagData"
                :props="cascaderProps"
              ></el-cascader>
            </el-form-item>
            <el-form-item label="设备标签">
              <el-select v-model="formInline.deviceCode" clearable>
                <el-option
                  v-for="item in deviceTagData"
                  :key="item.deviceCode"
                  :label="item.deviceName"
                  :value="item.deviceCode"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="设备类型标签">
              <el-select v-model="formInline.deviceDicCode" clearable>
                <el-option
                  v-for="item in sbData"
                  :key="item.dicCode"
                  :label="item.dicName"
                  :value="item.dicCode"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="元素标签">
              <el-select v-model="formInline.valueCode" clearable>
                <el-option
                  v-for="item in ysData"
                  :key="item.parameterCode"
                  :label="item.parameterName"
                  :value="item.parameterCode"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="聚合标签" prop="aggregationDicCode">
              <el-select v-model="formInline.aggregationDicCode" clearable>
                <el-option
                  v-for="item in aggregationRuleData"
                  :key="item.dicCode"
                  :label="item.dicName"
                  :value="item.dicCode"
                />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="queryPageByCardRealData">查询</el-button>
            </el-form-item>
          </el-form>
          <el-table max-height="300px" border :data="tableList" ref="tableRef2" reserve-selection row-key="id" @selection-change="handleSelectionChange">
            <el-table-column type="index" label="序号" width="60" align="center"/>
            <el-table-column prop="valueShowData" label="数据值" align="center"/>
            <el-table-column prop="valueAllName" label="数据值名称" align="center"/>
            <el-table-column prop="valueDataType" label="数据值类型" align="center">
              <template slot-scope="{row}">
                {{ row.valueDataType == 0 ? '一般类型' : '布尔类型'}}
              </template>
            </el-table-column>
            <el-table-column prop="customerCode" label="客户编码" align="center"/>
            <el-table-column prop="customerName" label="客户名称" align="center"/>
            <el-table-column prop="tagName" label="区域标签" show-overflow-tooltip align="center"/>
            <el-table-column prop="deviceName" label="设备标签" show-overflow-tooltip align="center"/>
            <el-table-column prop="deviceCode" label="设备编码" align="center"/>
            <el-table-column prop="deviceDicName" label="设备类型标签" align="center">
            </el-table-column>
            <el-table-column prop="valueName" label="参数编码" align="center"/>
            <el-table-column prop="aggregationDicName" label="聚合规则名称" align="center"/>
            <el-table-column label="操作" type="selection" width="50" align="center" />
          </el-table>
          <pagination
            class="pagination"
            :total="count"
            :page.sync="pageIndex"
        :limit.sync="pageSize"
        @pagination="getAccountData"
          />
        </div>
      </template>
      <template #footer>
        <el-button type="primary"  @click="addParamsSave">确定</el-button>
        <el-button @click="$refs.addParamsDialog.dialogVisible = false">取消
        </el-button>
      </template>
    </yc-dialog>
  </div>
</template>

<script>
  import ycDialog from "@/components/pageDialog"
  import { queryMyLayoutCard, queryCardList, choseCard, queryBindCardData, queryPageByCardRealData, queryCustomerCode, queryBooleanSpeak, bindCardData } from "@/api/systemBuilding/layout"
  // import {
  //   queryListByStatusAndCustomer,
  //   queryListByDevice,
  //   queryListByParams
  // } from "@/api/clientSetting/aggregateElementSetting"
  // import { queryListByTree } from "@/api/clientInfo/circuitBreaker";
  // import { queryListByTogeter } from "@/api/clientInfo/aggregateElement";
  import { getBasePic } from "@/api/systemBuilding/pcSystemBuilding"

  export default {
    components: {
      ycDialog,
    },
    data() {
      return {
        systemCode: "",
        menuCode: "",
        customerCode: "",
        loading: false,
        tableData: [],  //表格，二维数组
        layoutTableSet: [],  //合并的集合
        layoutIndexs: [],   //合并格子的index
        hasSetting: [], //已设置的数组

        centerTitle: "",
        dialogTitle: "",
        centerTitle2: "",
        dialogTitle2: "",
        cardList: [],
        searchCardName: "",
        indexNum: "",
        sizeType: "",
        cardCode: "",  //选择的组件
        cardLoading: false,

        formInline: {
          tagCode: [],
          deviceCode: "",
          deviceDicCode: '',
          valueCode: '',
          aggregationDicCode: ''
        },
        aggregationRuleData: [],
        deviceTagData: [],
        dimensionalityTagData: [],
        cascaderProps: {
          children: 'childList',
          value: 'tagCode',
          label: 'tagName',
          checkStrictly: true
        },
        ysData: [],
        sbData: [],

        typeList: [],
        tableList: [],  //添加参数列表数据集合
        selectList: [], //已选择参数
        picList: [],    //图片资源
        picUrl: "",
        picType: "",
        setDataLoading: false,
        count: 0,
        pageIndex: 1,
        pageSize: 10,
      }
    },
    created() {
      this.systemCode = this.$route.query.systemCode;
      this.menuCode = this.$route.query.menuCode;
      this.getAccountData();
      this.queryCustomerCode();
      this.getBasePicList();
    },
    methods: {
      /**
       * 获取布局方法
       */
      async getAccountData() {
        this.loading = true
        this.tableData = [];
        this.layoutTableSet = [];
        this.layoutIndexs = [];
        this.hasSetting = [];

        const {object} = await queryMyLayoutCard({
          systemCode: this.systemCode,
          menuCode: this.menuCode
        })
        let list = object || [];
        list.forEach(item => {
          this.layoutTableSet.push({
            index: item.indexNum,
            col: item.sizeType.split("*")[1],
            row: item.sizeType.split("*")[0],
            ...item
          })
          if(item.isBindCard == "Y") {  //Y绑定 N未绑定
            this.hasSetting.push({
              index: item.indexNum,
              cardPic: item.cardPic
            })

          }
          this.layoutIndexs.push(item.indexNum);
        })

        for(let i = 1; i <= 6; i++) {
          let arr = []
          for(let j = 1; j <= 12; j++) {
            arr.push(j + (i - 1) * 12);
          }
          this.tableData.push(arr);
        }
        this.loading = false
        this.$nextTick(() => {
          this.tableRowClassName();
        })
      },

      /**
       * 合并表格方法
       */
      arraySpanMethod({ row, column, rowIndex, columnIndex }) {
        let index = columnIndex + 1 + rowIndex * 12;
        for(let i in this.layoutTableSet) {
          if(this.layoutTableSet[i].index == index) {
            return [this.layoutTableSet[i].col || 1, this.layoutTableSet[i].row || 1];
          } else if(this.layoutTableSet[i].row && this.layoutTableSet[i].col) {
            let arr = [];
            for(let k = 0; k < this.layoutTableSet[i].col; k++) {
              for(let m = 0; m < this.layoutTableSet[i].row; m++) {
                if(k == 0 && m == 0) {
                  continue;
                }
                arr.push(this.layoutTableSet[i].index + m + k * 12);
              }
            }
            if(arr.includes(index)) {
              return [0, 0]
            }
          } else if(this.layoutTableSet[i].row && (index > this.layoutTableSet[i].index && index < this.layoutTableSet[i].index + this.layoutTableSet[i].row)) {
            return [0, 0]
          } else if(this.layoutTableSet[i].col && (index > this.layoutTableSet[i].index && (index - this.layoutTableSet[i].index) % 12 == 0 && (index - this.layoutTableSet[i].index) / 12 < this.layoutTableSet[i].col)) {
            return [0, 0]
          }
        }
      },

      // 行样式调整
      tableRowClassName() {
        let rows = document.getElementsByClassName("el-table__row");
        let arr = [];
        let obj = rows[0];
        let num = 1;
        let height = document.getElementsByTagName("tbody")[0].getBoundingClientRect().height / 6;
        for(let i = 0; i < rows.length; i++) {
          if(rows[i].childNodes.length == 0) {
            num ++;
            rows[i].className = "el-table__row row0";
            obj.style.height = height * num + "px";
          } else {
            obj = rows[i];
            num = 1;
          }
          arr.push(rows[i].childNodes.length);
        }
        return '';
      },


      isHasSetting(index) {
        return this.hasSetting.find(item => {
          return item.index == index;
        })
      },

      queryCustomerCode() {
        queryCustomerCode({
          systemCode: this.systemCode
        }).then(res => {
          if(res.status == 200) {
            this.customerCode = res.object.customerCode;
          }
        })
      },

      goBack() {
        this.$router.go(-1)
      },

      /**
       * 查询卡片
       */
      async searchCards() {
        const {status, object} = await queryCardList({
          cardSize: this.sizeType
        })
        if(status == 200) {
          this.cardList = object || [];
        }
      },

      /**
       * 配置卡片
       */
      cellClick(index) {
        this.dialogTitle = "卡片库"
        this.centerTitle = "卡片库"
        this.sizeType = "1*1";
        this.searchCardName = "";
        if(this.layoutTableSet.length > 0) {
          let obj = this.layoutTableSet.find(item => {
            return item.index == index;
          })
          if(obj) {
            this.indexNum = obj.index;
            this.sizeType = obj.row + "*" + obj.col;
          }

          if(obj.isBindCard == "Y") {
            this.cardCode = obj.cardCode;
          } else {
            this.cardCode = "";
          }

          // 根据块大小查询相对应的卡片
          this.searchCards();

          this.$refs.cardDialog.dialogVisible = true;
        }
      },

      /**
       * 配置卡片保存
       */
      async cardSave() {
        this.cardLoading = true;

        const {status, message} = await choseCard({
          systemCode: this.systemCode,
          menuCode: this.menuCode,
          indexNum: this.indexNum,
          cardCode: this.cardCode,
          title: this.searchCardName
        })
        if(status == 200) {
          this.getAccountData();
          this.$message.success(message);
          this.$refs.cardDialog.dialogVisible = false;
        }
        this.cardLoading = false;
      },

      /**
       * 配置参数
       */
      async setData(index) {
        this.dialogTitle = "配置参数"
        this.centerTitle = "配置参数"
        this.indexNum = index;
        this.selectList = [];

        const {status, object} = await queryBindCardData({
          systemCode: this.systemCode,
          menuCode: this.menuCode,
          indexNum: this.indexNum
        })
        if(status == 200) {
          this.selectList = object;
          for(let i = 0; i < this.selectList.length; i++) {
            await this.queryBooleanSpeak(this.selectList[i], i)
          }
        }
        this.$refs.setDataDialog.dialogVisible = true;
      },

      /**
       * 配置参数保存
       */
      async setDataSave(index) {
        this.setDataLoading = true;
        let list = this.selectList.map(item => {
          return {
            elementCode: item.elementCode,
            elementIconUrl: item.elementIconUrl,
            statusZeroIconUrl: item.statusZeroIconUrl,
            statusOneIconUrl: item.statusOneIconUrl
          }
        })
        const {status, message} = await bindCardData({
          systemCode: this.systemCode,
          menuCode: this.menuCode,
          indexNum: this.indexNum,
          mapString1: JSON.stringify(list)
        })
        if(status == 200) {
          this.$message.success(message);
          this.$refs.setDataDialog.dialogVisible = false;
        }
        this.setDataLoading = false;
      },

      /**
       * 添加参数
       */
      addParams() {
        this.dialogTitle2 = "添加参数"
        this.centerTitle2 = "添加参数"
        this.tableList = [];
        this.formInline = {
          tagCode: [],
          deviceCode: '',
          deviceDicCode: '',
          valueCode: '',
          aggregationDicCode: ''
        }
        this.queryListByTogeter();
        this.queryListByStatusAndCustomer();
        this.queryListByTree();
        this.queryListByParams();
        this.queryListByDevice();

        this.$refs.addParamsDialog.dialogVisible = true;
      },

      /**
       * 添加参数保存
       */
      async addParamsSave() {
        for(let i = 0; i < this.selectList.length; i++) {
          await this.queryBooleanSpeak(this.selectList[i], i)
        }

        this.$refs.addParamsDialog.dialogVisible = false
      },

      // 聚合数据规则 下拉框数据
      async queryListByTogeter() {
        const {object} = await queryListByTogeter()
        this.aggregationRuleData = object
      },
      // 设备标签 下拉框数据
      async queryListByStatusAndCustomer() {
        const {object} = await queryListByStatusAndCustomer({
          customerCode: this.customerCode
        })
        this.deviceTagData = object
      },

      // 区域标签列表 下拉框数据
      async queryListByTree() {
        const {object} = await queryListByTree({
          customerCode: this.customerCode
        })
        this.dimensionalityTagData = object
      },

      // 元素标签列表 下拉框数据
      async queryListByParams() {
        const {object} = await queryListByParams()
        this.ysData = object
      },

      // 设备类型标签列表 下拉框数据
      async queryListByDevice() {
        const {object} = await queryListByDevice()
        this.sbData = object
      },

      handleSelectionChange(val) {
        let arr = this.selectList.map(item => {
          return item.id;
        })
        // 防止重复添加
        if(val.length > 0) {
          val.forEach(item => {
            if(!arr.includes(item.id)) {
              this.selectList.push(item);
            }
          })
        }
      },

      async queryPageByCardRealData() {
        let tagCode = this.formInline.tagCode.length > 0 ? this.formInline.tagCode.join('-') : null
        let deviceCode = this.formInline.deviceCode ? this.formInline.deviceCode : null
        let valueCode = this.formInline.valueCode ? this.formInline.valueCode : null
        let deviceDicCode = this.formInline.deviceDicCode ? this.formInline.deviceDicCode : null
        let aggregationDicCode = this.formInline.aggregationDicCode ? this.formInline.aggregationDicCode : null

        const {object} = await queryPageByCardRealData({
          customerCode: this.customerCode,
          pageIndex: this.pageIndex,
          pageSize: this.pageSize,
          deviceCode: deviceCode,
          tagCode: tagCode,
          valueCode: valueCode,
          deviceDicCode: deviceDicCode,
          aggregationDicCode: aggregationDicCode
        })
        this.tableList = object.data
        this.count = object.count
      },

      pagination() {
        this.queryPageByCardRealData()
      },

      /**
       * 配置icon
       */
      async settingIcon(row, type) {
        this.curSelectObj = row;
        this.dialogTitle2 = "选择图片";
        this.centerTitle2 = "选择图片";
        this.picUrl = "";
        this.picType = type;
        this.$refs.iconDialog.dialogVisible = true;
      },

      // 查询布尔数据数据解释
      async queryBooleanSpeak(row, index) {
        if(row.valueDataType == 1) {
          const {status, object} = await queryBooleanSpeak({
            elementCode: row.elementCode
          })
          if(status == 200) {
            row.zeroValue = object.zeroValue;
            row.oneValue = object.oneValue;
          }
          this.selectList.splice(index, 1, {...row});
        }
      },

      /**
       * 选择图片保存
       */
      iconSave() {
        if(this.picType == 0) {
          this.curSelectObj.statusZeroIconUrl = this.picUrl;
        } else if(this.picType == 1) {
          this.curSelectObj.statusOneIconUrl = this.picUrl;
        } else {
          this.curSelectObj.elementIconUrl = this.picUrl;
        }

        this.$refs.iconDialog.dialogVisible = false;
      },

      // 查询icon
      getBasePicList() {
        getBasePic({picType: 1}).then(res => {
          if(res.status == 200) {
            this.picList = res.object;
          }
        })
      },

      /**
       * 删除数据
       */
      removeData(row) {
        let index = this.selectList.findIndex(item => {
          return row.id == item.id
        })
        if(index >= 0) {
          this.selectList.splice(index, 1);
        }
      },

      /**
       * 保存卡片配置
       */
      async saveCardSetting() {

      },
    }
  }
</script>

<style lang="scss" scoped>
  .home {
    width: 100%;
    height: calc(100vh - 50px);
    display: flex;
    flex-direction: column;
  }

  .layout {
    background: radial-gradient(#07424A 0%, #010B10 100%);
    flex: 1;

    .el-table {
      background-color: transparent;
      width: 100%;
      height: 100%;
      border: none;

      &::before {
        background-color: transparent;
      }

      ::v-deep.el-table__header-wrapper {
        display: none;
      }

      ::v-deep.el-table__body-wrapper, ::v-deep.el-table__body {
        width: 100%;
        height: 100%;

        tr {
          background-color: transparent;
          height: calc(100% / 6);

          &.row0 {
            height: 0;
          }

          &.el-table__row:hover {
            td {
              background-color: transparent;
            }
          }
        }

        td.el-table__cell {
          padding: 0;
          border: none;
        }

        .cell {
          height: 100%;
          padding: 8px;
        }
      }
    }

    .size1 {
      position: relative;
      background-color: transparent;
      width: 100%;
      height: 100%;
      box-shadow: 0px 0px 4px 0px #16D0FF;
      border: none;
      border-radius: 10px;
      display: flex;
      align-items: center;
      justify-content: center;

      &.hide {
        display: none;
      }

      &:focus {
        background-color: transparent;
        color: #606266;
      }

      ::v-deep.el-icon-plus:before {
        font-size: 30px;
      }

      &.checked, &:hover {
        color: #409EFF;
        background-color: rgba(0, 0, 0, 0.6) !important;
      }

      .setting {
        position: relative;
        background: #0075b9;
        color: #FFF;
        padding: 5px 10px;
        border-radius: 4px;
        z-index: 10;
      }

      .cardPic {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
      }
    }
  }

  .footer {
    height: 90px;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .cardtitle {
    width: auto;
    padding-bottom: 2px;
    margin-bottom: 5px;
    border-bottom: 2px solid #3276ff;
    display: inline-block;
  }

  .cardList {
    display: flex;
    flex-wrap: wrap;

    &>div {
      max-width: 30%;
      margin-bottom: 20px;
      margin-right: 10px;
    }

    img {
      width: 100%;
      margin-bottom: 10px;
      cursor: pointer;
    }
  }

  .el-select--small, .el-cascader--small {
    width: 150px;
  }

  .picdiv {
    width: 160px;
    height: 90px;
    display: flex;
    align-items: center;
    justify-content: center;

    .bgcss {
      max-width: 160px;
      max-height: 90px;
      cursor: pointer;
    }
  }

  .el-radio {
    display: flex;
    flex-direction: column-reverse;
    align-items: center;

    ::v-deep.el-radio__label {
      margin-bottom: 5px;
    }
  }
</style>
